package com.vincce.sport.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.Activity;
import com.vincce.sport.entity.ActivityBrand;
import com.vincce.sport.entity.ActivityOption;
import com.vincce.sport.entity.ActivityQuestion;
import com.vincce.sport.entity.ActivityUser;
import com.vincce.sport.entity.Page;
import com.vincce.sport.mapper.ActivityBrandMapper;
import com.vincce.sport.mapper.ActivityMapper;
import com.vincce.sport.mapper.ActivityOptionMapper;
import com.vincce.sport.mapper.ActivityQuestionMapper;
import com.vincce.sport.mapper.ActivityUserMapper;


@Controller
@RequestMapping("/activity")
public class ActivityController extends BaseController{
	@Resource
	private ActivityMapper activityMapper;
	
	@Resource
	private ActivityQuestionMapper activityQuestionMapper;
	
	@Resource
	private ActivityOptionMapper activityOptionMapper;
	
	@Resource
	private ActivityUserMapper activityUserMapper;
	
	@Resource
	private ActivityBrandMapper activityBrandMapper;
	
	
	/**
	 * 分页查询
	 * @param model
	 * @param page
	 * @param 
	 * @return
	 */
	@RequestMapping("/list")
	public String queryByPage(Model model,Page<Activity> page,Activity activity){
		Map<String, Object> filter = new HashMap<String, Object>();
		if(activity.getName() != null && !activity.getName().equals("")){
	            filter.put("name", activity.getName());
	    }
		if(activity.getBrandId() != null && !activity.getBrandId().equals("")){
            filter.put("brandId", activity.getBrandId());
		}
		
		page.setFilter(filter);
		page.setTotal(activityMapper.queryActivityCount(page.getFilter()));
		page.setResult(activityMapper.queryActivityByPage(page));
		
		List<ActivityBrand> activityBrandList = activityBrandMapper.queryByActivityBrandAll();
		
		model.addAttribute("activityBrandList",activityBrandList);
		model.addAttribute("activity",activity);
		model.addAttribute("page",page);
		return "/backstage/activityList";
	}
	
	/**
	 * 新增
	 * @param model
	 * @param activity
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public String add(Model model, Activity activity){
		Long count=0L;
        Map<String, Object> result = new HashMap<String, Object>();
        count=activityMapper.insertActivity(activity);
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
	
	@RequestMapping("/editHtml")
	public String updateHtml(Model model, Integer id){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		Activity activity = activityMapper.findActivityById(id);
		if(activity.getImgPath()!=null && !activity.getImgPath().equals("")){
			activity.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+activity.getImgPath(), "ori"));
		}
		
		List<ActivityBrand> activityBrandList = activityBrandMapper.queryByActivityBrandAll();
		
		ActivityQuestion activityQuestion = new ActivityQuestion();
		ActivityOption activityOption = null;
    	activityQuestion.setActivityId(activity.getId());
    	List<ActivityQuestion> activityQuestionList = activityQuestionMapper.findActivityQuestionByOne(activityQuestion);
    	if(activityQuestionList !=null && activityQuestionList.size()>0){
    		for(ActivityQuestion aq:activityQuestionList){
    			activityOption = new ActivityOption();
            	activityOption.setQuestionId(aq.getId());
            	List<ActivityOption> activityOptionList = activityOptionMapper.findActivityOptionByOne(activityOption);
            	aq.setActivityOptionList(activityOptionList);
    		}
    	}
    	
    	model.addAttribute("activity",activity);
		model.addAttribute("activityBrandList",activityBrandList);
		model.addAttribute("activityQuestionList",activityQuestionList);
		return "/backstage/addActivity";
	}
	
	/**
	 * 修改 
	 * @param model
	 * @param 
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ParseException 
	 */
	@RequestMapping("/update")
	@ResponseBody
	public String update(Model model, Activity activity,  
			@RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request) throws IOException, ParseException{
		if(request.getParameter("startTime")!=null && !request.getParameter("startTime").equals("")){
			activity.setStartTime(request.getParameter("startTime"));
		}
		if(request.getParameter("endTime")!=null && !request.getParameter("endTime").equals("")){
			activity.setEndTime(request.getParameter("endTime"));
		}
		Long count=0L;
 		String msg = "";
        Map<String, Object> result = new HashMap<String, Object>();
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        if(!CheckUtil.isEmpty(activity.getId())){
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
	                if (obj.statusCode == 200) {
	                	String path= obj.info.replaceAll("\\\\", "/");
	                	activity.setImgPath(path);
	                	count = activityMapper.updateActivity(activity);
	                }
				}
            } else {
            	count = activityMapper.updateActivity(activity);
            }
        }
        
        if(count != 0l){
        	int i=1;
        	ActivityQuestion activityQuestion = new ActivityQuestion();
        	ActivityOption activityOption = null;
        	
        	//添加前先清空问题
        	activityQuestion.setActivityId(activity.getId());
        	List<ActivityQuestion> activityQuestionList = activityQuestionMapper.findActivityQuestionByOne(activityQuestion);
        	if(activityQuestionList !=null && activityQuestionList.size()>0){
        		for(ActivityQuestion aq:activityQuestionList){
        			activityQuestionMapper.deleteById(aq.getId());
        		}
        	}
        	while(true){
        		String quesName = "quesName"+i;
        		String quesType = "quesType"+i;
        		if(request.getParameter(quesName)==null || request.getParameter(quesName).equals("")){
        			break;
        		}
        		
        		activityQuestion = new ActivityQuestion();
        		activityQuestion.setActivityId(activity.getId());
            	activityQuestion.setNum(i);
            	activityQuestion.setQuestion(request.getParameter(quesName));
            	if(request.getParameter(quesType)!=null && !request.getParameter(quesType).equals("")){
            		activityQuestion.setType(request.getParameter(quesType)==null?"0":request.getParameter(quesType));
        		}
            	count = activityQuestionMapper.insertActivityQuestion(activityQuestion);
            	
            	//清空选项
            	activityOption = new ActivityOption();
            	activityOption.setQuestionId(activityQuestion.getId());
            	List<ActivityOption> activityOptionList = activityOptionMapper.findActivityOptionByOne(activityOption);
            	if(activityOptionList !=null && activityOptionList.size()>0){
            		for(ActivityOption ao:activityOptionList){
            			activityOptionMapper.deleteById(ao.getId());
            		}
            	}
            	
            	int j=1;
            	while(true){
            		String optName = "optName"+i+""+j;
            		if(request.getParameter(optName)==null || request.getParameter(optName).equals("")){
            			break;
            		}
            		
            		activityOption = new ActivityOption();
            		activityOption.setActivityId(activity.getId());
            		activityOption.setQuestionId(activityQuestion.getId());
            		activityOption.setName(request.getParameter(optName));
            		activityOption.setOptOrder(j);
            		count = activityOptionMapper.insertActivityOption(activityOption);
            		
            		j++;
            	}
        		i++;
        	}
        	
        	
        }
        
        result.put("msg", msg);
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}
	
	
	/**
	 * 根据ID删除
	 * @param model
	 * @param id
	 * @return
	 */
	
	@RequestMapping("/deleteById")
	@ResponseBody
	public String deleteById(Model model,Integer id){
		Boolean flag=false;
		Integer count=activityMapper.deleteById(id);
		flag=count>0?true:false;
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}

	/**
	 * 导出
	 * @param
	 * @param id
	 * @throws ParseException 
	 */
	@RequestMapping("/export")
	public void export(HttpServletResponse response, HttpServletRequest request, Integer id) throws ParseException {
		Activity activity = activityMapper.findActivityById(id);
		
		String excelName = id+"";
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(excelName);
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("活动品牌");
		row.createCell(1).setCellValue(activity.getBrandName());

		row = sheet.createRow(1);
		row.createCell(0).setCellValue("活动名称");
		row.createCell(1).setCellValue(activity.getName());

		row = sheet.createRow(2);
		row.createCell(0).setCellValue("活动类型");
		if(activity.getType().equals("1")){
			row.createCell(1).setCellValue("竞猜活动");
		}else if(activity.getType().equals("2")){
			row.createCell(1).setCellValue("问卷调查");
		}

		row = sheet.createRow(3);
		row.createCell(0).setCellValue("活动周期时间");
		row.createCell(1).setCellValue(CheckUtil.isEmpty(activity.getStartTime()) ? "" : activity.getStartTime());
		row.createCell(2).setCellValue(CheckUtil.isEmpty(activity.getEndTime()) ? "" : activity.getEndTime());

		row = sheet.createRow(4);
		row.createCell(0).setCellValue("活动参与人数");
		ActivityUser activityUser = new ActivityUser();
		activityUser.setActivityId(id);
		List<ActivityUser> activityUserList = activityUserMapper.findUserforActivity(activityUser);
		if(activityUserList != null){
			row.createCell(1).setCellValue(activityUserList.size());
		} else{
			row.createCell(1).setCellValue("0");
		}

		row = sheet.createRow(5);
		ActivityQuestion activityQuestion = new ActivityQuestion();
		activityQuestion.setActivityId(id);
		List<ActivityQuestion> activityQuestionList = activityQuestionMapper.findActivityQuestionByOne(activityQuestion);
		if(activity.getType().equals("1")){
			row.createCell(0).setCellValue("竞猜问题");
			row.createCell(1).setCellValue(activityQuestionList.get(0).getQuestion());
			
			
			row = sheet.createRow(7);
			row.createCell(0).setCellValue("参与者名称");
			row.createCell(1).setCellValue("竞猜答案");
			if(activityUserList!=null && activityUserList.size()>0){
				for(int i=0;i<activityUserList.size();i++){
					row = sheet.createRow(8+i);
					row.createCell(0).setCellValue(activityUserList.get(i).getUserName());
					row.createCell(1).setCellValue(activityUserList.get(i).getAnswer());
				}
			}
			
		}else if(activity.getType().equals("2")){
			Map<String,Object> countMap = new HashMap<String, Object>();
			countMap.put("activityId", id);
			countMap.put("type", 1);
			Integer countNum = activityUserMapper.findOrFullByType(countMap);
			
			row.createCell(0).setCellValue("完整问卷");
			row.createCell(1).setCellValue(countNum);
			
			countMap.put("type", 2);
			countNum = activityUserMapper.findOrFullByType(countMap);
			row = sheet.createRow(6);
			row.createCell(0).setCellValue("不完整问卷");
			row.createCell(1).setCellValue(countNum);
			
			row = sheet.createRow(8);
			row.createCell(0).setCellValue("参与者名称");
			if(activityQuestionList!=null && activityQuestionList.size()>0){
				for(int i=1;i<=activityQuestionList.size();i++){
					row.createCell(i*2-1).setCellValue("问题"+i);
					row.createCell(i*2).setCellValue("答案"+i);
				}
			}
			
			if(activityUserList!=null && activityUserList.size()>0){
				for(int i=0;i<activityUserList.size();i++){
					row = sheet.createRow(9+i);
					row.createCell(0).setCellValue(activityUserList.get(i).getUserName());
					activityUser.setUserId(activityUserList.get(i).getUserId());
					activityUser.setUserName(activityUserList.get(i).getUserName());
					List<ActivityUser> activityUserList2 = activityUserMapper.findActivityUserByOne(activityUser);
					for(int j=1;j<=activityUserList2.size();j++){
						row.createCell(j*2-1).setCellValue(activityUserList2.get(j-1).getQuestion());
						row.createCell(j*2).setCellValue(activityUserList2.get(j-1).getAnswer());
					}
				}
			}
		}
		
		
		
		
		String filename = "activity_question_" + id + ".xls";
        response.setContentType("application/binary; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + new String(filename.toString().getBytes("UTF-8"), "iso8859-1")
                    + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		
	}
	      
}
